package com.ow.dva.module.fieldPay;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import com.ow.dva.config.ShopInfo;
import com.ow.dva.module.base.entity.KafkaMessage.FieldBean;
import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.base.service.KafkaService;
import com.ow.dva.module.order.entity.Order;
import com.ow.dva.module.order.service.OrderService;
import com.ow.dva.module.park.entity.Park;
import com.ow.dva.module.park.service.ParkService;
import com.ow.dva.module.terminal.service.TerminaService;
import com.ow.dva.util.pay.wxpay.*;
import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/fieldPay")
public class FieldPayController {

    @Resource
    private ParkService parkService;

    @Resource
    private TerminaService terminaService;

    @Resource
    private OrderService orderService;

    @Resource
    private KafkaService kafkaService;


    /**
     * 场内支付扫码
     * @param parkId
     * @return
     */
    @RequestMapping("/sweepCode")
    public String  sweepCode(String parkId,String terminaId, Model model){
        Park park = parkService.getById(parkId);
        if(park !=null){
            String parkName = park.getName();
            Map map = new HashMap();
            map.put("parkName",parkName);
            map.put("parkId",parkId);
            map.put("terminalId",terminaId);
            model.addAttribute("data",map);
        }
//        return  "redirect:/pay/onsite_index/";
        return  "pay/onsite_index";
    }

    /**
     * 根据停车场的ID和车牌号的ID获取订单信息
     * @param parkId
     * @param plate
     * @return
     */
    @RequestMapping("/getOrder")
    @ResponseBody
    public RT getOrder(String parkId, String plate,String terminalId)  {
        FieldBean fieldBean = new FieldBean();
        fieldBean.setParkId(parkId);
        fieldBean.setPlateNo(plate);
        String beanStr = JSONUtil.toJsonStr(fieldBean);
        try {
            Map map = new HashMap();
            map.put("beanStr",beanStr);
            String mess = JSON.toJSONString(map);
            kafkaService.sendMessage(3,terminalId,mess);
            Thread.sleep(1000);
            return  RT.ok();
        }catch (Exception e){
            e.printStackTrace();
            return  RT.error(2,"请求异常");
        }
    }

    /**
     * 获取新订单
     * @param parkId 停车场id
     * @param plate 车牌号
     * @return
     */
    @RequestMapping("/getNewsOrder")
    @ResponseBody
    public RT getNewOrder(String parkId, String plate,String terminalId,Integer num){
        Map map = new HashMap();
        map.put("parkId",parkId);
        map.put("status","0");
        map.put("plateNo",plate.trim().toUpperCase());
        List<Order> orders =orderService.selectByplateNo(map);
        if(orders.size()<=0){
            return  RT.error(num,"请求超时！");
        }else{
            Order order = orders.get(0);//获取到最新未支付的订单信息
            return  RT.ok("",order.getId());
        }
    }


    /**
     * 扫描后的确认订单页面
     * @return
     */

    @RequestMapping(value = "fieldSureOrder")//todo 不知道是否能获取到是什么设备扫码
    public String fieldSureOrder(String orderId,HttpServletRequest request){
        RT rt = orderService.isWxOrAli(request);
        if (rt.getMessage().equals("1") ){
            try {
                String aliUrl = orderService.uniformOrder(orderId);
                return "redirect:"+aliUrl;
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return "下单失败";
        }else if (rt.getMessage().equals("2")){
            String url = sureOrder(orderId);
            return "redirect:"+url;///必须重定向，否则不能成功
        }else {
            return "未知来源";
        }
    }

    @RequestMapping(value = "/sureOrder", method = RequestMethod.GET)
    public String sureOrder(String orderId) {
        String backUrl= ShopInfo.SERVER_URL+"/fieldPay/Back?orderId="+orderId;
//        String backUrl= ShopInfo.SERVER_URL+"/onSitePayController/Back";
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ ShopInfo.WX_GZ_APPID
                + "&redirect_uri="+ URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_base"
                + "&state=STATE#wechat_redirect";
        return url;///必须重定向，否则不能成功
    }


    @RequestMapping(value = "/Back", method = RequestMethod.GET)
    public String  Back(HttpServletRequest req, String orderId, HttpServletResponse res, Model modelMap) {
        String openid =getOpenid(req);
        System.out.println("---------------------------openId:"+openid+"-----------------------");
        if(openid!=null && !"".equals(openid)){
            Order order =orderService.getById(orderId);
            if(order !=null){
                System.out.println(order);
                try {
                   uniformOrder(req,res,order,openid,modelMap);
                } catch (JDOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                modelMap.addAttribute("order",order);
            }


        }
        return  "pay/onsite_order";
    }

    /**
     * 扫描统一下单
     * @param request
     * @param response
     * @param
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public void uniformOrder(HttpServletRequest request, HttpServletResponse response, Order order, String openId,Model model) throws JDOMException, IOException {
        System.out.println("--------------------扫描支付统一下单中(场内支付)-------------------------");
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        //订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr(); //获取客户端的真是的IP
        //订单号
        String out_trade_no =order.getId();
        Integer total_fee = (int)(order.getReallyMoney()*100);//TODO 总金额

        String body ="场内支付";
        //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", ShopInfo.WX_GZ_APPID);
        packageParams.put("mch_id", ShopInfo.WX_MCHID);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
//        packageParams.put("total_fee", String.valueOf(total_fee));
        packageParams.put("total_fee", String.valueOf(1));
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", ShopInfo.WX_FIELDPAY_NOTIFYURL);
        packageParams.put("trade_type", ShopInfo.WX_TRADETYPE_PROGRAM);
        packageParams.put("openid", openId);
        //请求签名
        String sign = PayCommonUtil.createSign(ShopInfo.CHARACTER, packageParams, ShopInfo.WX_KEY);
        packageParams.put("sign", sign);
        //转换为xml格式的请求串
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
//        //发送请求
        String resXml = HttpUtil.postData(ShopInfo.WX_URL, requestXML);
//        //返回内容转换为map
        Map map = XMLUtil.doXMLParse(resXml);
        String resultCode = (String) map.get("return_code");
        String prepay_id = (String) map.get("prepay_id");
        System.out.println("获取到的预支付ID："+ prepay_id);
        if("SUCCESS".equals(resultCode)){
            SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);;
            finalpackage.put("appId",map.get("appid"));//公众号id
            finalpackage.put("nonceStr",map.get("nonce_str")); // 支付签名随机串，不长于 32 位
            finalpackage.put("package","prepay_id=" + map.get("prepay_id")); // 支付签名随机串，不长于 32 位
            finalpackage.put("signType","MD5");
            finalpackage.put("timeStamp",timestamp);
            String finalsign = WXSignUtils.createSign("UTF-8", finalpackage, ShopInfo.WX_KEY);
            model.addAttribute("appId",map.get("appid"));////公众号id
            model.addAttribute("timeStamp", timestamp);//时间戳
            model.addAttribute("nonceStr", map.get("nonce_str"));//随机字符串
            model.addAttribute("packageValue","prepay_id=" + map.get("prepay_id"));//订单详情扩展字符串
            model.addAttribute("paySign", finalsign);
        }

    }

    /**
     * 微信登录认证后的回调
     * @return
     */
    public String getOpenid(HttpServletRequest req){
        //start 获取微信用户基本信息
        String code =req.getParameter("code");
        String str="https://api.weixin.qq.com/sns/oauth2/access_token";
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", ShopInfo.WX_GZ_APPID);
        paramMap.put("secret", ShopInfo.WX_GZ_AppSecret);
        paramMap.put("code", code);
        paramMap.put("grant_type", "authorization_code");
        String result= cn.hutool.http.HttpUtil.post(str, paramMap);
        try {
            Gson gson = new Gson();
            Map<String, Object> res   = gson.fromJson(result, new TypeToken<Map<String, Object>>() {}.getType());
            String openid=(String) res.get("openid");
            return  openid;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return  "";
        }
    }

    /**
     * 微信场内支付回调
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/fieldBillRecord",method=RequestMethod.POST)
    @ResponseBody
    public String fieldPay(HttpServletRequest request)throws IOException {
        BufferedReader reader = request.getReader();
        String line = "";
        StringBuffer inputString = new StringBuffer();
        String result = null;
        try {
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            Map<String, String> restmap = XMLUtil.doXMLParse(inputString.toString());
            if("SUCCESS".equals(restmap.get("result_code"))){
                String out_trade_no = restmap.get("out_trade_no");
                Order order = orderService.getById(out_trade_no);
                order.setOrderStatus(1);
                orderService.updateById(order);
//                kafkaService.sendMessage(9,termina.getCode(),"成功支付了场内订单！");
                kafkaService.sendMessage(9,order.getTerminalCode(),order);
                result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }


}
